package com.neusoft.elmboot.controller;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/GPTController")
public class GPTController {

    @RequestMapping("/getGPTResponse")
    public String getGPTResponse(String prompt) throws Exception {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        HttpPost request = new HttpPost("https://openai.api2d.net/v1/chat/completions");
        request.addHeader("Content-Type", "application/json");
        request.addHeader("Authorization", "Bearer fk203096-316AFk1q18BWnDjd4mAX6tbNXXzCx0Wg");

        // 设置请求体
        String requestJson = "{\"model\": \"gpt-3.5-turbo\", \"messages\": [{\"role\": \"user\", \"content\": \"" + prompt + "\"}]}";
        HttpEntity entity = new StringEntity(requestJson, ContentType.APPLICATION_JSON);
        request.setEntity(entity);

        CloseableHttpResponse response = httpClient.execute(request);

        try {
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                String jsonResponse = EntityUtils.toString(responseEntity);

                // 使用 Gson 解析 JSON
                JsonObject jsonObject = JsonParser.parseString(jsonResponse).getAsJsonObject();

                // 提取 Assistant 回复内容
                String assistantResponse = jsonObject.getAsJsonArray("choices")
                        .get(0).getAsJsonObject()
                        .getAsJsonObject("message")
                        .get("content")
                        .getAsString();

                return assistantResponse;
            }
        } finally {
            response.close();
        }

        return "";
    }
}